<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2018/12/17
 * Time: 16:08
 */
namespace app\api\controller;
use think\Db;
class Coupon extends Base
{
    /**
     * 异地登录验证
     * @return string|void
     */
    public function _initialize()
    {
        header('Access-Control-Allow-Origin:*');
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == 112){
            echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
            exit;
        }elseif($auth == 110){
            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            exit;
        }
    }
    
    /**
     * 商城首页(优惠券列表)
     */
    public function couponIndex(){
        extract(input());
        $this->couponDown();
        $today = date('Y-m-d H:i:s');
        $where = array();
        $where['coupon_status'] = 1;
        $where['coupon_end'] = array('>',$today);
        if(isset($keyword) && $keyword){
            $where['coupon_name'] = ['like','%' . $keyword . '%'];
        }
        //1、列表
        $data = Db::table('up_coupon')
            ->where($where)
            ->order('coupon_status ASC,coupon_end DESC,coupon_get_num ASC,coupon_time DESC')
            ->page($page,20)
            ->field('coupon_id,coupon_name,coupon_image,coupon_num,coupon_price,coupon_get_num')
            ->select();
        if($data){
            foreach ($data as $k=>$v){
                $data[$k]['mc_status'] = '';
                $have = Db::table('up_my_coupon')
                    ->where('mc_coupon_id',$v['coupon_id'])
                    ->where('mc_user_id',$user_id)
                    ->find();
                if($have){
                    $data[$k]['mc_status'] = $have['mc_status'];
                }
            }
        }
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 优惠券详情：
     */
    public function couponInfo(){
        extract(input());
        $this->couponDown();
        $where = array();
        $where['coupon_id'] = $coupon_id;
        //1、列表
        $data = Db::table('up_coupon c')
            ->join('up_my_coupon mc','c.coupon_id=mc.mc_coupon_id','LEFT')
            ->where($where)
            ->field('coupon_code',true)
            ->find();
        $data['mc_status'] = '';
        $have = Db::table('up_my_coupon')
            ->where('mc_coupon_id',$data['coupon_id'])
            ->where('mc_user_id',$user_id)
            ->find();
        if($have){
            $data['mc_status'] = $have['mc_status'];
        }
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 兑换
     */
    public function couponGet(){
        extract(input());
        $this->couponDown();
        $where = array();
        $where['coupon_id'] = $coupon_id;
        $coupon = Db::table('up_coupon')->where($where)->find();
        $user = Db::table('up_u_user')->where('user_id',$user_id)
            ->field('user_all_money,user_recharge,user_active_money')->find();
        $insert = [
            'mc_user_id'=>$user_id,
            'mc_coupon_id'=>$coupon_id
        ];
        $have = Db::table('up_my_coupon')->where($insert)->find();
        if($have){
            return json(['status'=>0,'msg'=>'您已经领过了']);
        }
        if($coupon['coupon_get_num'] >= $coupon['coupon_num']){
            return json(['status'=>0,'msg'=>'已经兑换完了']);
        }
        $none = Db::table('up_coupon_children')
            ->where('f_id',$coupon_id)
            ->where('coupon_children_type',1)
            ->where('coupon_children_status',1)
            ->find();
        if(!$none){
            return json(['status'=>0,'msg'=>'已经兑换完了']);
        }
        if($coupon['coupon_status'] != 1){
            return json(['status'=>0,'msg'=>'已下架']);
        }
        $i_have = $user['user_all_money']+$user['user_recharge']+$user['user_active_money'];
        if($coupon['coupon_price'] > $i_have){
            return json(['status'=>0,'msg'=>'金币不足']);
        }
        $insert['mc_time'] = date('Y-m-d H:i:s');
        $insert['mc_number'] = time() . rand(10000,9999);
        $insert['mc_coupon_code'] = $none['coupon_children_code'];
        Db::startTrans();
        try {
            Db::table('up_my_coupon')->insert($insert);
            Db::table('up_coupon')->where($where)->setInc('coupon_get_num');
            Db::table('up_coupon_children')->where('coupon_children_id',$none['coupon_children_id'])->setField('coupon_children_status',2);
            //扣钱了--start--
            $cp_price = $coupon['coupon_price'];
            if($user['user_recharge'] > 0){
                if($user['user_recharge'] >= $cp_price){
                    Db::table('up_u_user')->where('user_id',$user_id)->setDec('user_recharge',$cp_price);
                    $cp_price = 0;
                }else{
                    $cp_price = $cp_price - $user['user_recharge'];
                    Db::table('up_u_user')->where('user_id',$user_id)->setField('user_recharge',0);
                }
            }
            if($user['user_all_money'] > 0 && $cp_price > 0){
                if($user['user_all_money'] >= $cp_price){
                    Db::table('up_u_user')->where('user_id',$user_id)->setDec('user_all_money',$cp_price);
                    $cp_price = 0;
                }else{
                    $cp_price = $cp_price - $user['user_all_money'];
                    Db::table('up_u_user')->where('user_id',$user_id)->setField('user_all_money',0);
                }
            }
            if($user['user_active_money'] > 0 && $cp_price > 0){
                Db::table('up_u_user')->where('user_id',$user_id)->setDec('user_active_money',$cp_price);
            }
            //扣钱了-- end --
            //兑换成功就入明细
            allInDetail($user_id,2,'优惠券兑换',$coupon['coupon_price'],9);
            Db::commit();
            return json(['status'=>200,'msg'=>'OK']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['status'=>0,'msg'=>'领取失败']);
        }

    }
    /**
     * 我的优惠券（我的订单）：
     */
    public function myCoupon(){
        extract(input());
        $this->couponDown($user_id);
        $where = array();
        $where['mc_user_id'] = $user_id;
        if(isset($type) && $type){
            $where['mc_status'] = $type;
        }
        //1、列表
        $data = Db::table('up_my_coupon mc')
            ->join('up_coupon c','mc.mc_coupon_id=c.coupon_id','LEFT')
            ->where($where)
            ->order('mc_time DESC')
            ->field('mc_id,mc_number,mc_time,coupon_use_start,coupon_use_end,mc_status,coupon_name')
            ->page($page,15)
            ->select();
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 我的优惠券详情（我的订单详情）：
     */
    public function myCouponInfo(){
        extract(input());
        $this->couponDown($user_id);
        $where = array();
        $where['mc_id'] = $mc_id;
        //1、列表
        $data = Db::table('up_my_coupon mc')
            ->join('up_coupon c','mc.mc_coupon_id=c.coupon_id','LEFT')
            ->where($where)
            ->field('mc_id,mc_number,mc_time,coupon_use_start,coupon_use_end,mc_status,mc_coupon_code as coupon_code,coupon_name,mc_use_time')
            ->find();
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 点击使用（备用：看前端有没有此功能）
     */
    public function myCouponUse(){
        extract(input());
        $where = array();
        $where['mc_id'] = $mc_id;
        $status = Db::table('up_my_coupon')->where($where)->value('mc_status');
        if($status == 2){
            return json(['status'=>0,'msg'=>'您已经使用过了']);
        }
        if($status == 3){
            return json(['status'=>0,'msg'=>'已失效']);
        }
        //1、列表
        $res = Db::table('up_my_coupon')->where($where)->update(['mc_status'=>2,'mc_use_time'=>date('Y-m-d H:i:s')]);
        if($res){
            return json(['status'=>200,'msg'=>'ok']);
        }else{
            return json(['status'=>0,'msg'=>'使用失败']);
        }
    }
    /**
     * 点击删除（备用：看前端有没有此功能）
     */
    public function myCouponDel(){
        extract(input());
        $where = array();
        $where['mc_id'] = $mc_id;
        //1、列表
        $res = Db::table('up_my_coupon')->where($where)->delete();
        if($res){
            return json(['status'=>200,'msg'=>'ok']);
        }else{
            return json(['status'=>0,'msg'=>'删除失败']);
        }

    }

}